import axios from 'axios'
import qs from 'qs' 

import Version from '../../version'
class Request {

    static ERROR_API = 'ERROR_API'

    apiHost;

    secret;

    constructor() {       
        this.apiHost = Version.api_url;
        this.secret = '~!@#$`1234qwert';
    } 

    //"8ec749e9de775b4b6ae77f8c6cf3b7cf"
    wrap(_data) {
        var data = _data || {}
        data["timestamp"] = Math.floor(new Date().getTime() / 1000)
        var keys = Object.keys(data);
        keys.sort();
        var vals = [];
        keys.map(function (k) {
            vals.push(data[k])
        })
        var val = vals.join('');
        var sign = '';//md5(val + this.secret);
        return {
            "data": data,
            "sign": sign,
            "encryptType": 2,
            "responseType": "json"
        }
    }

    /**
     * 
     * @param {*} url 
     * @param {*} data  
     */
    post(url, data) {
        var wrap = data;//this.wrap(data);
        return axios.post(
            this.apiHost + url,
            // 2、将请求数据转换为form-data格式
            qs.stringify(wrap),
            // 3、设置请求头Content-Type
            { headers: { 'Content-Type': 'x-www-form-urlencoded' } },
        ).then(resp => {
            if (resp.status == 200) {
                var result = resp.data;
                
                return result
            } else {
                
                return { resultCode: resp.status, longMessage: resp.statusText }
            }
        }).catch(err => {
             
            return { resultCode: -101, longMessage: err.message }
        })
    }

    postJson(url, data) { 
        return axios.post(
            this.apiHost + url,  
            data,
            { headers: { 'Content-Type': 'application/json' } },
        ).then(resp => {
            if (resp.status == 200) {
                var result = resp.data; 
                return result
            } else {
                 
                return null;
            }
        }).catch(err => {
            
            return null;
        })
    }

    get(url, data) {
        var wrap = data;
        var params = qs.stringify(wrap)
        return axios.get(
            this.apiHost + url + "?" + params,
            // 3、设置请求头Content-Type
            { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } },
        ).then(resp => {
            if (resp.status == 200) {
                return resp.data
            } else {
               
                return null
            }
        }).catch(err => {
            
            return null;
        })
    }
} 

export default new Request();